#include "vao.h"

VAO::VAO(float *vData, GLuint vNum, GLuint *iData, GLuint iNum) : mVAO(0), mVBO(0), mEBO(0)
{
    initializeOpenGLFunctions();

    glGenBuffers(1, &mVBO);
    glBindBuffer(GL_ARRAY_BUFFER, mVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(*vData) * vNum, vData, GL_STATIC_DRAW);

    glGenVertexArrays(1, &mVAO);
    glBindVertexArray(mVAO);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void *)0);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void *)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void *)(6 * sizeof(float)));
    glEnableVertexAttribArray(2);

    if (iData != nullptr && iNum != 0)
    {
        glGenBuffers(1, &mEBO);  // ebo 一定要在vao 激活状态下进行绑定
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mEBO);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(*iData) * iNum, iData, GL_STATIC_DRAW);
    }

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);

}

void VAO::bind()
{
    glBindVertexArray(mVAO);
}

void VAO::unbind()
{
    glBindVertexArray(0);
}

VAO::~VAO()
{
    glDeleteBuffers(1, &mVBO);
    if (mEBO != 0)
    {
        glDeleteBuffers(1, &mEBO);
    }
    glDeleteVertexArrays(1, &mVAO);
}
